package com.jk1.bianligou.blg.job;

import com.jk1.bianligou.blg.domain.constant.OrderStatus;
import com.jk1.bianligou.blg.domain.po.Item;
import com.jk1.bianligou.blg.domain.po.Order;
import com.jk1.bianligou.blg.domain.po.OrderItem;
import com.jk1.bianligou.blg.service.ItemService;
import com.jk1.bianligou.blg.service.OrderItemService;
import com.jk1.bianligou.blg.service.OrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author WHH
 * 每5分钟检查一次未支付的订单（15分钟未支付则取消）
 */
@Service
public class OrderTimeoutService {

    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private ItemService itemService;

    @Scheduled(fixedRate = 5, timeUnit = TimeUnit.MINUTES)
    @Transactional(rollbackFor = Exception.class)
    public void checkAndCancelUnpaidOrders() {
        // 查询15分钟前创建的未支付订单
        LocalDateTime fifteenMinutesAgo = LocalDateTime.now().minusMinutes(15);
        List<Order> unpaidOrders = orderService.lambdaQuery()
                .eq(Order::getStatus, OrderStatus.DEFAULT)
                .le(Order::getCreateTime, fifteenMinutesAgo)
                .list();
        // 批量取消订单并恢复库存
        unpaidOrders.forEach(order -> {
            order.setStatus(OrderStatus.CANCEL);
            orderService.updateById(order);
            // 恢复库存
            OrderItem orderItem = orderItemService.lambdaQuery()
                    .eq(OrderItem::getOrderId, order.getId())
                    .one();
            if (orderItem != null) {
                itemService.lambdaUpdate()
                        .setSql("stock = stock + " + orderItem.getQuantity())
                        .eq(Item::getId, orderItem.getItemId())
                        .update();
            }
        });
    }
}